package com.gxar.quick.ar.server.db.service;

import com.gxar.common.entity.Result;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.quick.ar.server.base.async.works.event.WorksPreviewDeleteEvent;
import com.gxar.quick.ar.server.base.common.enums.ComboConfigItemEnum;
import com.gxar.quick.ar.server.base.common.enums.DeletedEnum;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.user.vo.response.UserRightsResponse;
import com.gxar.quick.ar.server.base.model.works.mapper.WorksPreviewMapStruct;
import com.gxar.quick.ar.server.base.model.works.vo.request.WorksPreviewCreateRequest;
import com.gxar.quick.ar.server.base.model.works.vo.response.WorksPreviewCreateResponse;
import com.gxar.quick.ar.server.base.model.works.vo.response.WorksPreviewInfoResponse;
import com.gxar.quick.ar.server.db.mapper.WorksPreviewMapper;
import com.gxar.quick.ar.server.db.model.WorksPreviewEntity;
import com.gxar.quick.ar.server.db.repository.WorksDraftRepository;
import com.gxar.quick.ar.server.db.repository.WorksPreviewRepository;
import com.gxar.quick.ar.server.db.repository.WorksRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author linsy
 * @version 1.0
 * @created 2023/11/24 15:08
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkPreviewService {

    private final WorksPreviewRepository worksPreviewRepository;
    private final WorksPreviewMapper worksPreviewMapper;
    private final ApplicationEventPublisher applicationEventPublisher;
    private final UserService userService;
    private final WorksService worksService;

    /**
     * 创建预览
     *
     * @param userProfile               用户信息
     * @param worksPreviewCreateRequest 请求
     * @return 响应
     */
    public WorksPreviewCreateResponse createPreview(UserProfile userProfile, WorksPreviewCreateRequest worksPreviewCreateRequest) {
        // 先校验用户
        userService.userInfo(userProfile);
        List<WorksPreviewEntity> worksPreviewEntityList = worksPreviewMapper.findByUserId(userProfile.getId());
        if (CollectionUtils.isNotEmpty(worksPreviewEntityList)) {
            String workDraftId = worksPreviewCreateRequest.getWorkDraftId();
            String worksId = worksPreviewCreateRequest.getWorksId();
            Set<String> resourceUrlSet = new HashSet<>();
            Set<String> worksLinkUrlSet = worksService.getWorksLinkUrl(worksId);
            if (CollectionUtils.isNotEmpty(worksLinkUrlSet)) {
                resourceUrlSet.addAll(worksLinkUrlSet);
            }
            Set<String> worksDraftLinkUrlSet = worksService.getWorksDraftLinkUrl(workDraftId);
            if (CollectionUtils.isNotEmpty(worksDraftLinkUrlSet)) {
                resourceUrlSet.addAll(worksDraftLinkUrlSet);
            }
            //发布消息 删除旧草稿
            applicationEventPublisher.publishEvent(new WorksPreviewDeleteEvent(this, userProfile.getId(), worksPreviewEntityList, resourceUrlSet));
        }
        Date date = new Date();
        WorksPreviewEntity entity = WorksPreviewMapStruct.INSTANCE.createToEntity(worksPreviewCreateRequest);
        entity.setCreatedAt(date);
        entity.setUpdatedAt(date);
        entity.setCreator(userProfile.getMobile());
        entity.setUserId(userProfile.getId());
        entity.setDeleted(DeletedEnum.FALSE.getCode());
        WorksPreviewEntity saved = worksPreviewRepository.save(entity);
        return WorksPreviewMapStruct.INSTANCE.entityToCreateResponse(saved);
    }

    /**
     * 预览详情
     *
     * @param userProfile 用户信息
     * @param id          预览id
     * @return 响应
     */
    public Result<WorksPreviewInfoResponse> getPreviewDetail(UserProfile userProfile, Long id) {
        Optional<WorksPreviewEntity> worksPreviewEntityOptional = worksPreviewRepository.findById(id);
        if (worksPreviewEntityOptional.isPresent()) {
            WorksPreviewEntity worksPreviewEntity = worksPreviewEntityOptional.get();
            if (worksPreviewEntity.getUserId().equals(userProfile.getId())
                    && DeletedEnum.FALSE.getCode().equals(worksPreviewEntity.getDeleted())) {
                UserRightsResponse userRightsResponse = userService.userRights(userProfile, ComboConfigItemEnum.WATERMARK.getItem());
                WorksPreviewInfoResponse worksPreviewInfoResponse = WorksPreviewMapStruct.INSTANCE.entityToInfoResponse(worksPreviewEntity);
                worksPreviewInfoResponse.setWatermark(userRightsResponse.getWatermark());
                return Result.success(worksPreviewInfoResponse);
            }
        }
        return Result.error(ResultCodeEnum.WORK_DRAFTS_NOT_EXIST);
    }

}
